package com.baroxtech.testanoterecorder;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.LinkedList;
import java.util.List;

public class StringAdapter extends RecyclerView.Adapter<StringAdapter.VH> {
    public static class VH extends RecyclerView.ViewHolder {
        public final TextView textView;

        public VH(View v) {
            super(v);
            textView = v.findViewById(R.id.text_view);
        }

        public void setString(String s) {
            textView.setText(s);
        }
    }

    private static final int LINE_LIMIT = 1000;
    private List<String> stringList;

    public StringAdapter() {
        stringList = new LinkedList<>();
    }

    public void add(String s) {
        String ss = s.trim();
        if (ss.isEmpty()) {
            return;
        }

        // 判定列表是否达到上限
        if (stringList.size() == LINE_LIMIT) {
            stringList.remove(0);
            notifyItemRemoved(0);
        }
        stringList.add(ss);
        notifyItemInserted(stringList.size() - 1);
    }

    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.string_adapter_layout, parent, false);
        return new StringAdapter.VH(v);
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position) {
        holder.setString(stringList.get(position));
    }

    @Override
    public int getItemCount() {
        return stringList.size();
    }

}
